package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Account;
import com.example.entity.Category;
import com.example.entity.Circles;
import com.example.exception.CustomException;
import com.example.mapper.CirclesMapper;
import com.example.mapper.GoodsMapper;
import com.example.mapper.PostsMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 圈子业务处理
 **/
@Service
public class CirclesService {

    @Resource
    private CirclesMapper circlesMapper;

    @Resource
    private PostsMapper postsMapper;

    /**
     * 新增
     */
    public void add(Circles circles) {
        List<Circles> list = circlesMapper.selectAll(null);
        for(Circles c : list){
            if(c.getName().equals(circles.getName())){
                throw new CustomException(ResultCodeEnum.Circles_EXIST_ERROR);
            }
        }
        circlesMapper.insert(circles);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        String circle = circlesMapper.selectById(id).getName();
        postsMapper.updateByCircleName(circle);
        circlesMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            circlesMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Circles circles) {
        List<Circles> list = circlesMapper.selectAll(null);
        for (Circles c : list) {
            if (!c.getId().equals(circles.getId()) && c.getName().equals(circles.getName())) {
                throw new CustomException(ResultCodeEnum.Circles_EXIST_ERROR);
            }
        }
        circlesMapper.updateById(circles);
    }

    /**
     * 根据ID查询
     */
    public Circles selectById(Integer id) {
        return circlesMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Circles> selectAll(Circles circles) {
        return circlesMapper.selectAll(circles);
    }

    /**
     * 分页查询
     */
    public PageInfo<Circles> selectPage(Circles circles, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Circles> list = circlesMapper.selectAll(circles);
        return PageInfo.of(list);
    }

}